package com.fr.chicken.filter;


import com.fr.chicken.annotation.Verification;
import com.fr.chicken.util.JwtUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class JwtAuthenticationFilter extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //token 校验
        Verification verification;
        if (handler instanceof HandlerMethod) {
            verification = ((HandlerMethod) handler).getMethodAnnotation(Verification.class);
        } else {
            return true;
        }
        //这里处理一些业务逻辑
        //有verification注解的方法需要进行登录校验
        String accessToken = "";
        if (verification != null) {
            accessToken = request.getHeader("accessToken");
            try {
                if (accessToken != null) {
                    String token = request.getHeader("accessToken");
                    //检查jwt令牌, 如果令牌不合法或者过期, 里面会直接抛出异常, 下面的catch部分会直接返回
                    JwtUtil.validateToken(token);
                }
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
                return false;
            }

        }

        return true;
    }
}